import { getGroupInfoListApi, getTokenIntervalApi, getUserInfoListApi } from "@/api/api_chatSocket/chatSocket_Api";
import { userJoinListStore } from "@/stores/userChatList";
import { getNow } from "@/utils/utils";
import { addUserListToDB } from "@/Dexie/UserDB";
import { addGroupListToDB } from "@/Dexie/GroupDB";

// 获取新token 并且每小时重新获取新的token防止重新登录
export const getNewToken = async (): Promise<number> => {
  if (localStorage["token"] && localStorage["account"]) {
    let newTokenResult = await getTokenIntervalApi();
    if (newTokenResult) {
      let { token } = newTokenResult.data.msg;
      localStorage["token"] = token;
      let timer: number = setInterval(async () => {
        let newTokenResult = await getTokenIntervalApi();
        if (newTokenResult) {
          let { token } = newTokenResult.data.msg;
          localStorage["token"] = token;
          localStorage["tokenExpireTime"] = new Date().getTime() + 72 * 60 * 60 * 1000;
        }
      }, 1000 * 60 * 60);
      return timer;
    }
  }
  return new Promise((resolve) => {
    resolve(0);
  });
};

// 获取朋友基础信息 -- 后续换成发布订阅
export const updateUserInfo = () => {
  // 获取好友/群列表
  let userJoinListStoreIns = userJoinListStore();
  const { joinList } = storeToRefs(userJoinListStoreIns);
  let timer:number = setInterval(async () => {
    if (joinList.value.length === 0) {
      return;
    }
    clearInterval(timer);
    let accountList:string[] = [];
    let nowTime = localStorage['updateUserInfoTime'] || 0;
    joinList.value.filter(item => item._type === 0).forEach(el => {
      accountList.push(el._friend_account);
    });
    let result = await getUserInfoListApi(accountList, nowTime);
    let userInfoList = result.data.msg.userBaseInfo;
    await addUserListToDB(userInfoList);
    localStorage['updateUserInfoTime'] = getNow();
  }, 50);
};
// 获取群基础信息-- 后续换成发布订阅
export const updateGroupInfo = () => {
  // 获取好友/群列表
  let userJoinListStoreIns = userJoinListStore();
  const { joinList } = storeToRefs(userJoinListStoreIns);
  let timer:number = setInterval(async () => {
    if (joinList.value.length === 0) {
      return;
    }
    clearInterval(timer);
    let groupList:string[] = [];
    let nowTime = localStorage['updateGroupInfoTime'] || 0;
    joinList.value.filter(item => item._type === 1).forEach(el => {
      groupList.push(el._friend_account);
    });
    let result = await getGroupInfoListApi(groupList, nowTime);
    let userInfoList = result.data.msg.groupInfo;
    await addGroupListToDB(userInfoList);
    localStorage['updateGroupInfoTime'] = getNow();
  }, 50);
};
